package be.kuleuven.mume.rest;

import java.util.logging.Level;
import java.util.logging.Logger;

import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;

import org.json.JSONException;
import org.json.JSONObject;

import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.FilterOperator;
import com.google.appengine.api.datastore.Query.SortDirection;

import be.kuleuven.mume.JSONHelper;
import be.kuleuven.mume.beans.PersoonBean;
import be.kuleuven.mume.exceptions.UserNotLoggedInException;
import be.kuleuven.mume.query.PersoonQuery;
import be.kuleuven.mume.query.QueryHelper;

@Path("/tweet")
public class Tweet {
	private static final Logger log = Logger.getLogger(Tweet.class.getName());

	@GET
	@Path("/")
	@Produces ("application/json")
	public String doGet(@QueryParam("rpp")@DefaultValue("10")int rpp, 
			@QueryParam("page")@DefaultValue("0")int page,
			@QueryParam("hashtag")@DefaultValue("*")String hashTag){
		try {
			Query query = new Query("Tweet");
			query.addSort("datestamp", SortDirection.DESCENDING);
			if(!hashTag.equals("*"))
				query.addFilter("set", FilterOperator.EQUAL, hashTag);
			return JSONHelper.getQueryAsJSON(query, "Tweet", rpp, page).toString();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return JSONHelper.ERROR;
	}
	
	@POST
	@Path("/add")
	@Produces("application/json")
	public String addTweet(String jsonTweet){
		try {
			JSONObject result = new JSONObject(jsonTweet);
			String cont = "www.google.com";
			if(result.has("continue"))
			 cont = result.getString("continue");
			
			QueryHelper<PersoonBean> h = PersoonQuery.getCurrentPersoonQuery(cont, false);
			PersoonBean p = h.executeQuery();
			
			if(!p.hasTwitter()) {
				return "{\"error\": \"twitter token not found. Please use the link to allow MobiLEnvi to your twitter account.\"" + 
				", \"link\" : \"/mobilenvi/twittersignin?continue=" + cont + "\"}";
			}
			
			String tweet = result.getString("tweet");
			
			p.getTwitter().updateStatus(tweet);
			
			h.close();
			
			return JSONHelper.SUCCES;
		} catch (UserNotLoggedInException e) {
			return e.toJsonString();
		} catch (JSONException e) {
			log.log(Level.SEVERE, "JSONException", e);
		} catch (Exception e) {
			log.log(Level.SEVERE, "Exception", e);
		}
		
		return JSONHelper.ERROR;
	}
}
